package com.qf.springcloud.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

@Component
public class RateLimiterFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 50;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 令牌桶，每秒放一个令牌~
    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public Object run() throws ZuulException {
        if (rateLimiter.tryAcquire()) {
            System.out.println("拿到令牌往里走~~~");
        }else{
            System.out.println("没拿到令牌，拜拜啦！！！");
        }
        return null;
    }
}
